package com.wmc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wmc.mapper.ClazzMapper;
import com.wmc.pojo.Clazz;
import com.wmc.pojo.ClazzQueryParam;
import com.wmc.pojo.PageResult;
import com.wmc.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;


    @Override
    public void save(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        //新增之后状态不会根据上面说的条件进行显示开课还是未开课
        if (clazz.getEndDate() != null && clazz.getEndDate().isBefore(LocalDate.now())) {
            clazz.setStatus("已结课");
        } else if (clazz.getBeginDate() != null && clazz.getBeginDate().isAfter(LocalDate.now())) {
            clazz.setStatus("未开班");
        } else {
            clazz.setStatus("在读中");
        }



        clazzMapper.save(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);

    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> list() {

        return clazzMapper.listcouse();

    }

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> list = clazzMapper.list(clazzQueryParam);
        Page<Clazz> p = (Page<Clazz>) list;
        //如果如果- 当前时间 > 结课时间：状态（studus）未 已结课。当前时间 < 开课时间：状态未 未开班。否则，就是 在读中
        for (Clazz clazz : list) {
            if (clazz.getEndDate() != null && clazz.getEndDate().isBefore(LocalDate.now())) {
                clazz.setStatus("已结课");
            } else if (clazz.getBeginDate() != null && clazz.getBeginDate().isAfter(LocalDate.now())) {
                clazz.setStatus("未开班");
            } else {
                clazz.setStatus("在读中");
            }
        }
        //新增之后状态不会根据上面说的条件进行显示开课还是未开课




        return new PageResult<Clazz>(p.getTotal(), p.getResult());
    }

    @Override
    public void deleteById(Integer id) {
        //在页面原型中，要求如果该班级下关联的有学生，是不允许删除的，并提示错误信息："对不起, 该班级下有学生, 不能直接删除"

        Integer studentByClazzID = clazzMapper.countStudentByClazzID(id);
        if (studentByClazzID > 0){
            throw new RuntimeException("对不起, 该班级下有学生, 不能直接删除");
        }
        clazzMapper.deleteById(id);
    }


}
